package com.yz.rabbitmq.exchange.topic;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.yz.rabbitmq.ChannelsUtil;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 **/
public class TopicExchangeCon {

    public  TopicExchangeCon(String exchangeName, String queueName , String bindKey){
        Channel channel = ChannelsUtil.getChannel();
        try {
            channel.queueDeclare(queueName,true,false,false,null);
            channel.queueBind(queueName,exchangeName,bindKey);
            channel.basicConsume(queueName, false, new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println(queueName+" :队列接收到了 "+new String(body));
//                    if(queueName.contains(".#"))
//                        channel.basicAck(envelope.getDeliveryTag(),false);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    public static void main(String[] args) throws Exception {
        Channel channel = ChannelsUtil.getChannel();
        String exchange = "topicExchange";
        channel.exchangeDeclare(exchange, "topic",true);
        ChannelsUtil.closeChannel(channel);
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            new TopicExchangeCon(exchange, "bing 'usa.#' queue", "usa.#");
        }).start();
        new Thread(()->{
            new TopicExchangeCon(exchange, "bing '#.new' queue", "#.news");
        }).start();
        new Thread(()->{
            new TopicExchangeCon(exchange, "bing '#.weather' queue", "#.weather");
        }).start();
        new Thread(()->{
            new TopicExchangeCon(exchange, "bing 'europe.#' queue", "europe.#");
        }).start();
    }
}
